#!/usr/bin/env python

import sys
import os.path
import os
import time
import django
import mimetypes
import json

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import User
from accounts.views import loginAction
from home.views import indexView
from home.files import createFolder, getMetaInformation, convertFormat
from home.images import getFirstImageFigureID, getImage
from home.recommend import do_my_work_recommender
from home.annotate import setTagSelected, finalize

class TPost:
    def __init__(self):
        self.data = {}
        pass

    def get(self, key, default_value):
        if key in self.data:
            return self.data[key]

        return default_value

    def set(self, key, value):
        self.data[key] = value

    data = {}

class TRequest:
    def __init__(self):
        self.POST = TPost()
        self.session = {}

    POST = TPost()
    session = {}

def login():
    request = TRequest()
    request.POST.set('username', 'kinuxroot')
    request.POST.set('password', 'sakaimasamipass')
    
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    isAllowAutoLogin = request.POST.get('isAllowAutoLogin', True)
    
    print username
    print password
    print isAllowAutoLogin
    
    response = loginAction(request)
    print response

    return request

def cutContentType(string):
    return string.replace("Content-Type: application/json", "")

django.setup()
figuresCount = 0
username = ""

if len(sys.argv) == 1 or len(sys.argv) == 2:
    print 'Please specify the argument.'
    quit()
else:
    username = sys.argv[1]
    print "username = " + username
    figuresCount = int(sys.argv[2])
    print "figuresCount = " + str(figuresCount)

figureID = getFirstImageFigureID(username)
if figureID == -1:
    quit()

image = getImage(username, figureID, 0)
print image
imageStr = cutContentType(str(image))
image = json.loads(imageStr)
figureID = image["figureID"]
sendOntologies = "FMA,PW,NIFSTD,NCIT,CL,CHEBI,DOID,RXNORM,GO,BAO,XCO,FBbi,SNOMEDCT,PR,"

figureIndex = 0

while figureID != -1 and figureIndex < figuresCount :
    print "Process figure " + str(figureID)

    figureLegend = image["figureLegend"]

    if figureLegend == "":
        print "Figure lengend is empty, using figure title instead."
        figureLegend = image["figureTitle"];

    lowerFigureLegend = figureLegend.lower()

    if figureLegend != "":
        recommendTags =  do_my_work_recommender(figureID, figureLegend, sendOntologies, username)

        tagsCount = 0
        for tag in recommendTags:
            tagID = tag['tagID']
            tagName = tag['tagName']

            if lowerFigureLegend.find(tagName.lower()) != -1:
                tagResult = setTagSelected(figureID, tagID, "true", username)
                print "tagID:%(tagID)s tagName:%(tagName)s result:%(tagResult)s" % {
                    "tagID": tagID, "tagName": tagName, "tagResult": tagResult }
                tagsCount = tagsCount + 1

        if tagsCount > 0:
            finalize(figureID)
            print "finalize: " + str(figureID)

    image = getImage(username, figureID, 1)
    imageStr = cutContentType(str(image))
    image = json.loads(imageStr)
    figureID = image["figureID"]
    figureIndex = figureIndex + 1

    time.sleep(2)
